package com.gome.boot.config.schedule;

import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

/**
 * 基础同步Schedule配置.
 *
 * @author baoxiufeng
 */
public abstract class BaseScheduleConfig implements SchedulingConfigurer {

    @Bean
    public ThreadPoolTaskScheduler taskScheduler() {
        return createScheduler(getSchedulerTaskPoolSize());
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.setTaskScheduler(this.taskScheduler());
    }

    /**
     * 创建指定线程池大小的定时任务.
     *
     * @param poolSize 处理定时任务可用的线程池大小
     * @return 定时任务对象
     */
    protected ThreadPoolTaskScheduler createScheduler(int poolSize) {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(poolSize);
        scheduler.setThreadNamePrefix("task-");
        scheduler.setAwaitTerminationSeconds(5);
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        return scheduler;
    }

    /**
     * 定时任务执行需要使用到的线程池大小.
     * <br/>由子类根据实际情况给出需要的线程池大小.
     * <br/>一般设置为定义的定时任务数量即可.
     *
     * @return 使用到的线程池大小
     */
    protected abstract int getSchedulerTaskPoolSize();
}
